//
//  XS_Check.swift
//  EKLWisdomP3
//
//  Created by 韩云智 on 2020/10/19.
//

import Foundation

extension String {
    //MARK: 校验字符串
    /// 校验正则
    enum XS_Regex: String {
        /// 校验车牌号
        case carNumber = "^[\\u4e00-\\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5,6}$"
        /// 校验身份证号
        case cardId = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$"
        /// 校验输入金额, 允许"."结尾
        case money = "(^[1-9]([0-9]+)?(.[0-9]{0,2})?$)|(^[0][.]{0,1}$)|(^0.[0-9]([0-9])?$)"
        /// 校验密码 8-14位数字字母下划线
        case password = "^[a-zA-Z0-9_]{8,14}$"
        /// 校验手机号 1开头11位数
        case phone = "^1+\\d{10}$"
        /// 校验支付密码 6位数字
        case payPassword = "^(\\d{6}$)"
    }
    
    func xsCheck(_ regex: XS_Regex) -> Bool {
        return xsCheckRegex(regex.rawValue)
    }
    /// 校验通用
    /// - Parameter regex: 正则表达式字符串
    func xsCheckRegex(_ regex: String) -> Bool {
        let pred = NSPredicate(format: "SELF MATCHES %@", regex)
        return pred.evaluate(with: self)
    }
}

/// 转码
public extension String {
    //MARK: 转码
    /// 密文
    /// - Parameter pre: 前几位不遮挡, 默认0
    /// - Parameter suf: 后几位不遮挡, 默认0
    func cipher(pre: Int = 0, suf: Int = 0) -> String {
        let sufCount = count - suf + 1
        var index = 0
        let str = map { (Character) -> Character in
            index += 1
            if index > pre, index < sufCount {
                return "*"
            }
            return Character
        }
        return String(str)
    }
    
    /// 文件地址处理
    func cropPrefix(_ prefix: String = "file://") -> String {
        if hasPrefix(prefix) {
            return String(suffix(count - prefix.count))
        }
        return self
    }
    
    /// 日期格式转数字
    func toInt(_ separator: String = ":") -> Int {
        let arr = self.components(separatedBy: separator)
        guard arr.count > 1 else {
            return -1
        }
        var num: Int = 0
        for (index, char) in arr.reversed().enumerated() {
            var count = Int(char) ?? 0
            for _ in 0..<index {
                count *= 100
            }
            num += count
        }
        return num
    }
}
